﻿using System;
using System.Collections;
using FlowCanvas;
using FlowCanvas.Nodes;
using NodeCanvas.Framework;
using ParadoxNotion.Design;
using UnityEngine;
using UnityEngine.Playables;

namespace Yoozoo.Gameplay.Liberty.Nodes
{
    [Category("Ggame")]
    public class PlayQTETimeline : LatentActionNodeBase
    {
        [RequiredField]
        public BBParameter<string> timelineName;
        public BBParameter<float> stopTime;
        public BBParameter<bool> stopBgm;
        public BBParameter<DirectorWrapMode> wrapMode = DirectorWrapMode.None;

        [HideInInspector]
        public FlowOutput onStart;
        [HideInInspector]
        public FlowOutput onPreStart;

        [HideInInspector]
        public FlowOutput onEventA;
        [HideInInspector]
        public FlowOutput onEventB;

        private bool stopped = false;

        private bool bgmStatus = true;
        
        public override bool allowRoutineQueueing { get { return false; } }

        public IEnumerator Invoke()
        {
            stopped = false;
            //bgmStatus = 
            BlueprintUtils.TimelineManager.PlayQTETimeline(timelineName.value, parentNode);
            BlueprintUtils.PlayTimeline(timelineName.value,OnStopped,OnStart,OnPreStart,wrapMode.value);
            if (stopTime.value > 0.01)
            {
                yield return new WaitForSeconds(stopTime.value);
                try
                {
                    BlueprintUtils.StopTimeline(timelineName.value);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
            else
            {
                yield return new UnityEngine.WaitUntil(() =>
                {
                    return stopped;
                });
            }
        }

        private void OnStart(PlayableDirector director)
        {
            onStart?.Call(new Flow());

        }

        private void OnPreStart()
        {
            onPreStart?.Call(new Flow());
        }

        private void OnStopped(PlayableDirector director)
        {
            var qteInfo = BlueprintUtils.TimelineManager.GetPlayingQTETimelineInfo();
            if (qteInfo!=null)
            {
                Graph.SendGlobalEvent(qteInfo.ResultEvent, null, qteInfo.node);
            }
            stopped = true;
        }

        protected override void OnRegisterDerivedPorts(FlowNode node)
        {
            onPreStart = node.AddFlowOutput("onPrePlay");
            onStart = node.AddFlowOutput("onPlay");

            node.AddFlowInput("In", (f) => { Begin(Invoke(), f); });
            
        }
        
    }
}